package com.hackcloud.shardingjdbc.sharding;

import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

import java.util.*;

public class ComplexShardingStrategy implements ComplexKeysShardingAlgorithm {
    private final static String TABLE_PREFIX = "tb_user_%d_%d";
    private final int shardingCount = 3;
    static Map<Integer, List<String>> SCENE = new HashMap<>();

    static {
        SCENE.put(0, Arrays.asList("060401", "060501", "010401", "010501", "010801", "070401", "070402"));
        SCENE.put(1, Arrays.asList("050401", "050501", "020401", "020501", "020801"));
        SCENE.put(2, Arrays.asList("040201", "040101"));
    }


    @Override
    public Collection<String> doSharding(Collection collection, ComplexKeysShardingValue complexKeysShardingValue) {
        try {
            final String tableName = getTableName(complexKeysShardingValue);
            return Collections.singleton(tableName);
        } catch (Exception e) {

        }
        Collection<String> tables = new ArrayList<>();
        Set<Integer> types = SCENE.keySet();
        for (Integer type : types) {
            for (int i = 0; i < shardingCount; i++) {
                tables.add(String.format(TABLE_PREFIX, type, i));
            }
        }
        return tables;
    }

    private String getTableName(ComplexKeysShardingValue complexKeysShardingValue) {
        final Map map = complexKeysShardingValue.getColumnNameAndShardingValuesMap();
        LinkedList certNos = (LinkedList) map.get("cert_no");
        String certNo = (String) certNos.getFirst();
        certNo = certNo.replace("X", "0").replace("x", "0");
        long xx = Long.valueOf(certNo);
        LinkedList scenes = (LinkedList) map.get("scene");
        String scene = (String) scenes.getFirst();
        final Integer key = SCENE.entrySet().stream().filter(x -> x.getValue().contains(scene)).findFirst().orElse(null).getKey();
        String tableName = String.format(TABLE_PREFIX, key, xx % shardingCount);
        return tableName;
    }
}
